// 创建用户相关的小仓库
import { defineStore } from 'pinia'

import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'
import type {
  LoginFormData,
  LoginResponseData,
  UserInfoResponseData,
} from '@/api/user/type'

import type { UserState } from '@/store/modules/types/type'
// 引入操作本地数据的工具方法
import { SET_TOEKN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'

import { constantRoute } from '@/router/routes'

let useUserStore = defineStore('User', {
  // 状态
  state: (): UserState => {
    return {
      token: GET_TOKEN(),
      menuRoutes: constantRoute, //仓库存储生成菜单需要数组
      username: '',
      avatar: '',
    }
  },
  actions: {
    // 登录
    async userLogin(loginForm: LoginFormData) {
      //登陆请求
      let result: LoginResponseData = await reqLogin(loginForm)

      if (result.code === 200) {
        // 保存token
        this.token = result.data as string
        SET_TOEKN(result.data as string)

        return 'OK'
      } else {
        // 提示错误result

        return Promise.reject(new Error(result.message))
      }
    },
    async userInfo() {
      //获取用户信息
      let result: UserInfoResponseData = await reqUserInfo()

      if (result.code === 200) {
        this.username = result.data.name
        this.avatar = result.data.avatar
        return 'OK'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
    async logout() {
      let result: any = await reqLogout()
      if (result.code === 200) {
        // 退出登录
        this.token = ''
        this.username = ''
        this.avatar = ''
        REMOVE_TOKEN()
        return 'OK'
      } else {
        return Promise.reject(new Error(result.message))
      }
      console.log(result)

      // console.log($router.currentRoute.value.fullPath)

      // $router.push({ path: '/login', query: { redirect: $router.currentRoute.value.fullPath } })
    },
  },
  getters: {},
})

export default useUserStore
